package com.sinoglobal.ningxia.wxapi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.dumping.R;
import com.sinoglobal.dumping.activity.Dumpling_DumplingsShareActivity;
import com.sinoglobal.dumping.api.Dumpling_RemoteImpl;
import com.sinoglobal.dumping.base.Dumpling_SinoAsyncTask;
import com.sinoglobal.dumping.base.Dumpling_SinoBaseActivity;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.dumping.bean.Dumpling_DumplingPaySuccessVo;
import com.sinoglobal.dumping.bean.Dumpling_DumplingPayVo;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.wallet.activity.W_RechargeDetailsActivity;
import com.sinoglobal.wallet.api.RemoteImpl;
import com.sinoglobal.wallet.app.SinoConstans;
import com.sinoglobal.wallet.entity.RsWechat;
import com.sinoglobal.wallet.entity.W_OrderStateEntiy;
import com.sinoglobal.wallet.task.MyAsyncTask;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class WXPayEntryActivity extends Dumpling_SinoBaseActivity implements IWXAPIEventHandler {

    private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";
    private String isRecharge = "-1";//1,充值成功。0，充值失败。2待充值,3.提交成功
    private static String orderId;//订单号
    private IWXAPI api;
    private static Dumpling_DumplingPayVo.DumplingPayListVo D_weChat;

    private static String str;//金额数目
    private int payStyle = 4;//微信支付支付方式标识
    private static String type = "";//判断是钱包传来的数据，（接入捞一捞也有）
    private static String source;//来自充值记录详情的微信支付数据标示
    private static RsWechat weChat;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dumpling_wechat_notice);

        api = WXAPIFactory.createWXAPI(this, Dumpling_SinoConstans.DUMPLING_WeCHATID);

        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq rep) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onResp(BaseResp resp) {
        // TODO Auto-generated method stub
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            if ("Dumpling".equals(type)) {//捞一捞传来的数据
                if ("0".equals(String.valueOf(resp.errCode))) {
                    Toast.makeText(FlyApplication.context, "支付成功", Toast.LENGTH_SHORT).show();
                    isRecharge = "1";
                    dumpingPaySuccessNet();
                } else if ("-2".equals(String.valueOf(resp.errCode))) {
                    Toast.makeText(FlyApplication.context, "支付取消", Toast.LENGTH_SHORT).show();
                    isRecharge = "2";
                    finish();
                } else if ("-1".equals(String.valueOf(resp.errCode))) {
                    Toast.makeText(FlyApplication.context, "支付失败", Toast.LENGTH_SHORT).show();
                    finish();
                }
            } else if ("wallet".equals(type)) {//钱包模块传来的数据;
                if ("0".equals(String.valueOf(resp.errCode))) {
                    Toast.makeText(FlyApplication.context, "支付成功", Toast.LENGTH_SHORT).show();
                    isRecharge = "1";
                    sendDestoryRDBroadcast();
                    if ("Record".equals(source)) {
                        sendDestoryRRDBroadcast();
                    }
                    getOrderState(weChat.getTrade_sn());
                } else if ("-2".equals(String.valueOf(resp.errCode))) {
                    Toast.makeText(FlyApplication.context, "支付取消", Toast.LENGTH_SHORT).show();
                    isRecharge = "2";
                    sendDestoryRDBroadcast();
                    if ("Record".equals(source)) {
                        sendDestoryRRDBroadcast();
                    }
                    LogUtils.v("充值详情---2-2-" + weChat.getAppId());
                    Bundle bundle = new Bundle();
                    bundle.putString("isRecharge", isRecharge);
                    bundle.putString("Money", str);
                    bundle.putString("Source", source);//通知下个页面是从记录页面传过来的数据
                    bundle.putInt("payStyle", payStyle);
                    bundle.putSerializable("WeChat", weChat);//支付宝签名
                    goIntent(W_RechargeDetailsActivity.class, bundle);
                    finish();
                } else if ("-1".equals(String.valueOf(resp.errCode))) {
                    Toast.makeText(FlyApplication.context, "支付失败", Toast.LENGTH_SHORT).show();
                    if ("Record".equals(source)) {
                        sendDestoryRRDBroadcast();
                    }
                    finish();
                }
            }
        }

    }

    public static class WechatReciver extends BroadcastReceiver {

        public WechatReciver() {

        }

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(SinoConstans.KEY_WechatReceiver)) {
                type = intent.getStringExtra("Type");
                if ("Dumpling".equals(type)) {//捞一捞传来的数据
                    D_weChat = (Dumpling_DumplingPayVo.DumplingPayListVo) intent.getSerializableExtra("WeChat");
                    orderId = intent.getStringExtra("Orderid");
                } else if ("wallet".equals(type)) {//钱包模块传来的数据
                    weChat = (RsWechat) intent.getSerializableExtra("WeChat");//设置密码成功后传来的、
                    str = intent.getStringExtra("Money");
                    source = intent.getStringExtra("Source");

                }


            }


        }
    }


    //---------------------wallet-------------------------
    private void getOrderState(final String orderSn) {
        MyAsyncTask<W_OrderStateEntiy> task = new MyAsyncTask<W_OrderStateEntiy>(true, this, true) {
            @Override
            public W_OrderStateEntiy before(Void... params) throws Exception {
                // TODO 测试接口
                return RemoteImpl.getInstance().getOrderState(WXPayEntryActivity.this, orderSn);
            }

            @Override
            public void after(W_OrderStateEntiy result) {
                if (result != null) {
                    if (result.getCode().equals("100")) {
                        String orderState = result.getRs();
                        if ("3".equals(orderState)) {//支付订单状态1：支付中、2：已回调、3：支付成功、4：异常订单
                            isRecharge = "1";
                        } else {
                            isRecharge = "3";
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString("isRecharge", isRecharge);
                        bundle.putString("Money", str);
                        bundle.putString("Source", source);//通知下个页面是从记录页面传过来的数据
                        bundle.putInt("payStyle", payStyle);
                        bundle.putSerializable("WeChat", weChat);//支付宝签名
                        goIntent(W_RechargeDetailsActivity.class, bundle);
                        finish();
                    } else {
                        Toast.makeText(FlyApplication.context, result.getMsg(), Toast.LENGTH_SHORT).show();
                        Bundle bundle = new Bundle();
                        bundle.putString("isRecharge", isRecharge);
                        bundle.putString("Money", str);
                        bundle.putString("Source", source);//通知下个页面是从记录页面传过来的数据
                        bundle.putInt("payStyle", payStyle);
                        bundle.putSerializable("WeChat", weChat);//支付宝签名
                        goIntent(W_RechargeDetailsActivity.class, bundle);
                        finish();
                    }
                }

            }

            @Override
            public void exception() {
            }
        };
        task.execute();
    }

    public void goIntent(Class<?> toClsActivity, Bundle bundle) {
        Intent intent = new Intent(this, toClsActivity);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    private void sendDestoryRDBroadcast() {//发送销毁W_RechargeDetailsActivity的广播
        Intent intent = new Intent();
        intent.setAction(SinoConstans.KEY_DestoryReceiver);
        sendBroadcast(intent);
    }

    private void sendDestoryRRDBroadcast() {//发送销毁W_RechargeRecordDetailsActivity的广播
        Intent intent = new Intent();
        intent.setAction(SinoConstans.KEY_DestoryReceiverTwo);
        sendBroadcast(intent);
    }

//----------------------Dumpling-------------

    @Override
    public void onAntiViolence(View view) {

    }

    //2003 用户包饺子后查询支付状态-第三方支付（获取分享链接）
    private void dumpingPaySuccessNet() {

        new Dumpling_SinoAsyncTask<Void, Void, Dumpling_DumplingPaySuccessVo>(WXPayEntryActivity.this, false, true) {
            @Override
            public Dumpling_DumplingPaySuccessVo before(Void... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().DumplingPaySuccess(orderId);
            }

            @Override
            public void after(Dumpling_DumplingPaySuccessVo result) {
                if (result != null) {
                    if (result.getCode() == 100) {
                        String paySuccessId = result.getResultList().getPannikinId().toString();
                        Intent pay_intent = new Intent();
                        pay_intent.setClass(WXPayEntryActivity.this, Dumpling_DumplingsShareActivity.class);
                        pay_intent.putExtra("paySuccessId", paySuccessId);
                        startActivity(pay_intent);
                        finish();
                    } else {
                        Toast.makeText(FlyApplication.context, result.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void exception() {

            }
        }.execute();

    }

}